package danny.hoi.web.controller.system;


import com.github.pagehelper.PageInfo;
import danny.hoi.domain.export.system.*;
import danny.hoi.service.export.system.DeptService;
import danny.hoi.service.export.system.RoleService;
import danny.hoi.service.export.system.UserService;
import danny.hoi.web.controller.base.BaseController;
import danny.hoi.web.utils.Md5Utils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 1.分页显示企业信息
     * 2.请求地址:user/list.do
     * 3.响应地址:WEB-INF/pages/user/user-list.jsp
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize,
                       String key) {
        if (key == null) {
            key = "";
        }
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        //设置条件查询
        criteria.andUserNameLike("%" + key + "%");
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        PageInfo<User> pageInfo = userService.findByPages(example, pageNum, pageSize);

        request.setAttribute("key", key);
        request.setAttribute("pageInfo", pageInfo);
        return "system/user/user-list";
    }

    /**
     * 1.前往添加页面
     * 2.请求地址:/user/toAdd.do
     * 3.响应地址:WEB-INF/pages/user/user-add.jsp
     */
    @RequestMapping("/toAdd")
    public String toAdd() {
        DeptExample example = new DeptExample();
        DeptExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        List<Dept> deptList = deptService.findAll(example);
        request.setAttribute("deptList", deptList);
        return "system/user/user-add";
    }

    /**
     * 1.前往修改页面
     * 2.请求地址:/user/toUpdate.do
     * 3.响应地址:WEB-INF/pages/user/user-update.jsp
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        DeptExample example = new DeptExample();
        DeptExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        List<Dept> deptList = deptService.findAll(example);
        User user = userService.findById(id);
        request.setAttribute("user", user);
        request.setAttribute("deptList", deptList);
        return "system/user/user-update";
    }


    /**
     * 1.更新页面
     * 2.请求地址:/user/edit.do
     * 3.响应地址:redirect:/user/list.do
     */
    @RequestMapping("/edit")
    public String edit(User user) {
        if ("".equals(user.getDeptId())) {
            user.setDeptId(null);
        }
        user.setCompanyId(getLoginCompanyId());
        user.setCompanyName(getLoginCompanyName());

        if (StringUtils.isEmpty(user.getUserId())) {
            //添加新用户,发送邮件
            if (!StringUtils.isEmpty(user.getEmail())) {
                Map<String, String> map = new HashMap<>();
                String to = user.getEmail();
                String subject = "欢迎加入saas货代云平台";
                String content = "人生若只如初见,何事秋风悲画扇.等闲变却故人心,古人却道心易变";
                map.put("to", to);
                map.put("subject", subject);
                map.put("content", content);
                rabbitTemplate.convertAndSend("msg.email", map);
            }
            //添加
            user.setCreateBy(getLoginUser().getUserId());
            user.setCreateTime(new Date());
            //密码加密加盐
            user.setPassword(Md5Utils.getMd5(user.getPassword(), user.getEmail()));
            userService.save(user);
        } else {
            //更新
            user.setUpdateBy(getLoginUser().getUserId());
            user.setUpdateTime(new Date());
            //判断密码是否修改了，如果修改了需要对新的密码加密加盐
            User dbUser = userService.findById(user.getUserId());
            if (!dbUser.getPassword().equals(user.getPassword())) {
                user.setPassword(Md5Utils.getMd5(user.getPassword(), user.getEmail()));
            }
            userService.update(user);
        }

        return "redirect:/system/user/list.do";
    }

    /**
     * 1.删除
     * 2.请求地址: "/user/delete.do?id=" + id;
     * 3.响应地址: 异步响应
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, String> delete(String id) {
        Map<String, String> map = new HashMap<>();
        if (userService.delete(id)) {
            map.put("msg", "删除成功");
        } else {
            map.put("msg", "删除失败,请联系管理员");
        }
        return map;
    }

    /**
     * 1.前往用户角色页面
     * 2.请求地址：/system/user/roleList.do
     * 3.响应地址：WEB-INF/pages/system/user/user-role.jsp
     */
    @RequestMapping("roleList")
    public String roleList(String id) {
        //查询当前用户角色
        User user = userService.findById(id);
        request.setAttribute("user", user);
        //查询角色列表
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        List<Role> roleList = roleService.findAll(example);
        request.setAttribute("roleList", roleList);

        //查询当前用户拥有的角色，拼接成字符串
        List<Role> roles = roleService.findRoleByUserId(id);
        StringBuilder sb = new StringBuilder();
        for (Role role : roles) {
            sb.append(role.getRoleId()).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        request.setAttribute("userRoleStr", sb.toString());
        return "system/user/user-role";
    }

    /**
     * 1.修改角色
     * 2.请求地址： /system/user/changeRole.do
     * 3.响应地址："redirect:/system/user/list.do";
     */
    @RequestMapping("/changeRole")
    private String changeRole(String userId, String[] roleIds) {
        roleService.changeRole(userId, roleIds);
        return "redirect:/system/user/list.do";
    }

}
